home *** CD-ROM | disk | FTP | other *** search
/ MacHack 2000 / MacHack 2000.toast / pc / The Hacks / MacHacksBug / Python 1.5.2c1 / Lib / telnetlib.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2000-06-23  |  17.5 KB  |  561 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 1.5)
  3.  
  4. '''TELNET client class.
  5.  
  6. Based on RFC 854: TELNET Protocol Specification, by J. Postel and
  7. J. Reynolds
  8.  
  9. Example:
  10.  
  11. >>> from telnetlib import Telnet
  12. >>> tn = Telnet(\'www.python.org\', 79)   # connect to finger port
  13. >>> tn.write(\'guido\r
  14. \')
  15. >>> print tn.read_all()
  16. Login       Name               TTY         Idle    When    Where
  17. guido    Guido van Rossum      pts/2        <Dec  2 11:10> snag.cnri.reston..
  18.  
  19. >>>
  20.  
  21. Note that read_all() won\'t read until eof -- it just reads some data
  22. -- but it guarantees to read at least one byte unless EOF is hit.
  23.  
  24. It is possible to pass a Telnet object to select.select() in order to
  25. wait until more data is available.  Note that in this case,
  26. read_eager() may return \'\' even if there was data on the socket,
  27. because the protocol negotiation may have eaten the data.  This is why
  28. EOFError is needed in some cases to distinguish between "no data" and
  29. "connection closed" (since the socket also appears ready for reading
  30. when it is closed).
  31.  
  32. Bugs:
  33. - may hang when connection is slow in the middle of an IAC sequence
  34.  
  35. To do:
  36. - option negotiation
  37. - timeout should be intrinsic to the connection object instead of an
  38.   option on one of the read calls only
  39.  
  40. '''
  41. import sys
  42. import socket
  43. import select
  44. import string
  45. DEBUGLEVEL = 0
  46. TELNET_PORT = 23
  47. IAC = chr(255)
  48. DONT = chr(254)
  49. DO = chr(253)
  50. WONT = chr(252)
  51. WILL = chr(251)
  52. theNULL = chr(0)
  53.  
  54. class Telnet:
  55.     """Telnet interface class.
  56.  
  57.     An instance of this class represents a connection to a telnet
  58.     server.  The instance is initially not connected; the open()
  59.     method must be used to establish a connection.  Alternatively, the
  60.     host name and optional port number can be passed to the
  61.     constructor, too.
  62.  
  63.     Don't try to reopen an already connected instance.
  64.  
  65.     This class has many read_*() methods.  Note that some of them
  66.     raise EOFError when the end of the connection is read, because
  67.     they can return an empty string for other reasons.  See the
  68.     individual doc strings.
  69.  
  70.     read_until(expected, [timeout])
  71.         Read until the expected string has been seen, or a timeout is
  72.         hit (default is no timeout); may block.
  73.  
  74.     read_all()
  75.         Read all data until EOF; may block.
  76.  
  77.     read_some()
  78.         Read at least one byte or EOF; may block.
  79.  
  80.     read_very_eager()
  81.         Read all data available already queued or on the socket,
  82.         without blocking.
  83.  
  84.     read_eager()
  85.         Read either data already queued or some data available on the
  86.         socket, without blocking.
  87.  
  88.     read_lazy()
  89.         Read all data in the raw queue (processing it first), without
  90.         doing any socket I/O.
  91.  
  92.     read_very_lazy()
  93.         Reads all data in the cooked queue, without doing any socket
  94.         I/O.
  95.  
  96.     """
  97.     
  98.     def __init__(self, host = None, port = 0):
  99.         '''Constructor.
  100.  
  101.         When called without arguments, create an unconnected instance.
  102.         With a hostname argument, it connects the instance; a port
  103.         number is optional.
  104.  
  105.         '''
  106.         self.debuglevel = DEBUGLEVEL
  107.         self.host = host
  108.         self.port = port
  109.         self.sock = None
  110.         self.rawq = ''
  111.         self.irawq = 0
  112.         self.cookedq = ''
  113.         self.eof = 0
  114.         if host:
  115.             self.open(host, port)
  116.         
  117.  
  118.     
  119.     def open(self, host, port = 0):
  120.         """Connect to a host.
  121.  
  122.         The optional second argument is the port number, which
  123.         defaults to the standard telnet port (23).
  124.  
  125.         Don't try to reopen an already connected instance.
  126.  
  127.         """
  128.         self.eof = 0
  129.         if not port:
  130.             port = TELNET_PORT
  131.         
  132.         self.host = host
  133.         self.port = port
  134.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  135.         self.sock.connect((self.host, self.port))
  136.  
  137.     
  138.     def __del__(self):
  139.         '''Destructor -- close the connection.'''
  140.         self.close()
  141.  
  142.     
  143.     def msg(self, msg, *args):
  144.         '''Print a debug message, when the debug level is > 0.
  145.  
  146.         If extra arguments are present, they are substituted in the
  147.         message using the standard string formatting operator.
  148.  
  149.         '''
  150.         if self.debuglevel > 0:
  151.             print 'Telnet(%s,%d):' % (self.host, self.port),
  152.             if args:
  153.                 print msg % args
  154.             else:
  155.                 print msg
  156.         
  157.  
  158.     
  159.     def set_debuglevel(self, debuglevel):
  160.         '''Set the debug level.
  161.  
  162.         The higher it is, the more debug output you get (on sys.stdout).
  163.  
  164.         '''
  165.         self.debuglevel = debuglevel
  166.  
  167.     
  168.     def close(self):
  169.         '''Close the connection.'''
  170.         if self.sock:
  171.             self.sock.close()
  172.         
  173.         self.sock = 0
  174.         self.eof = 1
  175.  
  176.     
  177.     def get_socket(self):
  178.         '''Return the socket object used internally.'''
  179.         return self.sock
  180.  
  181.     
  182.     def fileno(self):
  183.         '''Return the fileno() of the socket object used internally.'''
  184.         return self.sock.fileno()
  185.  
  186.     
  187.     def write(self, buffer):
  188.         '''Write a string to the socket, doubling any IAC characters.
  189.  
  190.         Can block if the connection is blocked.  May raise
  191.         socket.error if the connection is closed.
  192.  
  193.         '''
  194.         if IAC in buffer:
  195.             buffer = string.replace(buffer, IAC, IAC + IAC)
  196.         
  197.         self.msg('send %s', `buffer`)
  198.         self.sock.send(buffer)
  199.  
  200.     
  201.     def read_until(self, match, timeout = None):
  202.         '''Read until a given string is encountered or until timeout.
  203.  
  204.         When no match is found, return whatever is available instead,
  205.         possibly the empty string.  Raise EOFError if the connection
  206.         is closed and no cooked data is available.
  207.  
  208.         '''
  209.         n = len(match)
  210.         self.process_rawq()
  211.         i = string.find(self.cookedq, match)
  212.         if i >= 0:
  213.             i = i + n
  214.             buf = self.cookedq[:i]
  215.             self.cookedq = self.cookedq[i:]
  216.             return buf
  217.         
  218.         s_reply = ([
  219.             self], [], [])
  220.         s_args = s_reply
  221.         if timeout is not None:
  222.             s_args = s_args + (timeout,)
  223.         
  224.         while not (self.eof) and apply(select.select, s_args) == s_reply:
  225.             i = max(0, len(self.cookedq) - n)
  226.             self.fill_rawq()
  227.             self.process_rawq()
  228.             i = string.find(self.cookedq, match, i)
  229.             if i >= 0:
  230.                 i = i + n
  231.                 buf = self.cookedq[:i]
  232.                 self.cookedq = self.cookedq[i:]
  233.                 return buf
  234.             
  235.         return self.read_very_lazy()
  236.  
  237.     
  238.     def read_all(self):
  239.         '''Read all data until EOF; block until connection closed.'''
  240.         self.process_rawq()
  241.         while not (self.eof):
  242.             self.fill_rawq()
  243.             self.process_rawq()
  244.         buf = self.cookedq
  245.         self.cookedq = ''
  246.         return buf
  247.  
  248.     
  249.     def read_some(self):
  250.         """Read at least one byte of cooked data unless EOF is hit.
  251.  
  252.         Return '' if EOF is hit.  Block if no data is immediately
  253.         available.
  254.  
  255.         """
  256.         self.process_rawq()
  257.         while not (self.cookedq) and not (self.eof):
  258.             self.fill_rawq()
  259.             self.process_rawq()
  260.         buf = self.cookedq
  261.         self.cookedq = ''
  262.         return buf
  263.  
  264.     
  265.     def read_very_eager(self):
  266.         """Read everything that's possible without blocking in I/O (eager).
  267.         
  268.         Raise EOFError if connection closed and no cooked data
  269.         available.  Return '' if no cooked data available otherwise.
  270.         Don't block unless in the midst of an IAC sequence.
  271.  
  272.         """
  273.         self.process_rawq()
  274.         while not (self.eof) and self.sock_avail():
  275.             self.fill_rawq()
  276.             self.process_rawq()
  277.         return self.read_very_lazy()
  278.  
  279.     
  280.     def read_eager(self):
  281.         """Read readily available data.
  282.  
  283.         Raise EOFError if connection closed and no cooked data
  284.         available.  Return '' if no cooked data available otherwise.
  285.         Don't block unless in the midst of an IAC sequence.
  286.  
  287.         """
  288.         self.process_rawq()
  289.         while not (self.cookedq) and not (self.eof) and self.sock_avail():
  290.             self.fill_rawq()
  291.             self.process_rawq()
  292.         return self.read_very_lazy()
  293.  
  294.     
  295.     def read_lazy(self):
  296.         """Process and return data that's already in the queues (lazy).
  297.         
  298.         Raise EOFError if connection closed and no data available.
  299.         Return '' if no cooked data available otherwise.  Don't block
  300.         unless in the midst of an IAC sequence.
  301.  
  302.         """
  303.         self.process_rawq()
  304.         return self.read_very_lazy()
  305.  
  306.     
  307.     def read_very_lazy(self):
  308.         """Return any data available in the cooked queue (very lazy).
  309.  
  310.         Raise EOFError if connection closed and no data available.
  311.         Return '' if no cooked data available otherwise.  Don't block.
  312.  
  313.         """
  314.         buf = self.cookedq
  315.         self.cookedq = ''
  316.         if not buf and self.eof and not (self.rawq):
  317.             raise EOFError, 'telnet connection closed'
  318.         
  319.         return buf
  320.  
  321.     
  322.     def process_rawq(self):
  323.         """Transfer from raw queue to cooked queue.
  324.  
  325.         Set self.eof when connection is closed.  Don't block unless in
  326.         the midst of an IAC sequence.
  327.  
  328.         """
  329.         buf = ''
  330.         
  331.         try:
  332.             while self.rawq:
  333.                 c = self.rawq_getchar()
  334.                 if c == theNULL:
  335.                     continue
  336.                 
  337.                 if c == '\x11':
  338.                     continue
  339.                 
  340.                 if c != IAC:
  341.                     buf = buf + c
  342.                     continue
  343.                 
  344.                 c = self.rawq_getchar()
  345.                 if c == IAC:
  346.                     buf = buf + c
  347.                 elif c in (DO, DONT):
  348.                     opt = self.rawq_getchar()
  349.                     if not c == DO and 'DO':
  350.                         pass
  351.                     self.msg('IAC %s %d', 'DONT', ord(c))
  352.                     self.sock.send(IAC + WONT + opt)
  353.                 elif c in (WILL, WONT):
  354.                     opt = self.rawq_getchar()
  355.                     if not c == WILL and 'WILL':
  356.                         pass
  357.                     self.msg('IAC %s %d', 'WONT', ord(c))
  358.                 else:
  359.                     self.msg('IAC %s not recognized' % `c`)
  360.         except EOFError:
  361.             pass
  362.  
  363.         self.cookedq = self.cookedq + buf
  364.  
  365.     
  366.     def rawq_getchar(self):
  367.         '''Get next char from raw queue.
  368.  
  369.         Block if no data is immediately available.  Raise EOFError
  370.         when connection is closed.
  371.  
  372.         '''
  373.         if not (self.rawq):
  374.             self.fill_rawq()
  375.             if self.eof:
  376.                 raise EOFError
  377.             
  378.         
  379.         c = self.rawq[self.irawq]
  380.         self.irawq = self.irawq + 1
  381.         if self.irawq >= len(self.rawq):
  382.             self.rawq = ''
  383.             self.irawq = 0
  384.         
  385.         return c
  386.  
  387.     
  388.     def fill_rawq(self):
  389.         '''Fill raw queue from exactly one recv() system call.
  390.  
  391.         Block if no data is immediately available.  Set self.eof when
  392.         connection is closed.
  393.  
  394.         '''
  395.         if self.irawq >= len(self.rawq):
  396.             self.rawq = ''
  397.             self.irawq = 0
  398.         
  399.         buf = self.sock.recv(50)
  400.         self.msg('recv %s', `buf`)
  401.         self.eof = not buf
  402.         self.rawq = self.rawq + buf
  403.  
  404.     
  405.     def sock_avail(self):
  406.         '''Test whether data is available on the socket.'''
  407.         return select.select([
  408.             self], [], [], 0) == ([
  409.             self], [], [])
  410.  
  411.     
  412.     def interact(self):
  413.         '''Interaction function, emulates a very dumb telnet client.'''
  414.         if sys.platform == 'win32':
  415.             self.mt_interact()
  416.             return None
  417.         
  418.         while 1:
  419.             (rfd, wfd, xfd) = select.select([
  420.                 self,
  421.                 sys.stdin], [], [])
  422.             if self in rfd:
  423.                 
  424.                 try:
  425.                     text = self.read_eager()
  426.                 except EOFError:
  427.                     print '*** Connection closed by remote host ***'
  428.                     break
  429.  
  430.                 if text:
  431.                     sys.stdout.write(text)
  432.                     sys.stdout.flush()
  433.                 
  434.             
  435.             if sys.stdin in rfd:
  436.                 line = sys.stdin.readline()
  437.                 if not line:
  438.                     break
  439.                 
  440.                 self.write(line)
  441.             
  442.  
  443.     
  444.     def mt_interact(self):
  445.         '''Multithreaded version of interact().'''
  446.         import thread
  447.         thread.start_new_thread(self.listener, ())
  448.         while 1:
  449.             line = sys.stdin.readline()
  450.             if not line:
  451.                 break
  452.             
  453.             self.write(line)
  454.  
  455.     
  456.     def listener(self):
  457.         '''Helper for mt_interact() -- this executes in the other thread.'''
  458.         while 1:
  459.             
  460.             try:
  461.                 data = self.read_eager()
  462.             except EOFError:
  463.                 print '*** Connection closed by remote host ***'
  464.                 return None
  465.  
  466.             if data:
  467.                 sys.stdout.write(data)
  468.             else:
  469.                 sys.stdout.flush()
  470.  
  471.     
  472.     def expect(self, list, timeout = None):
  473.         """Read until one from a list of a regular expressions matches.
  474.  
  475.         The first argument is a list of regular expressions, either
  476.         compiled (re.RegexObject instances) or uncompiled (strings).
  477.         The optional second argument is a timeout, in seconds; default
  478.         is no timeout.
  479.  
  480.         Return a tuple of three items: the index in the list of the
  481.         first regular expression that matches; the match object
  482.         returned; and the text read up till and including the match.
  483.  
  484.         If EOF is read and no text was read, raise EOFError.
  485.         Otherwise, when nothing matches, return (-1, None, text) where
  486.         text is the text received so far (may be the empty string if a
  487.         timeout happened).
  488.  
  489.         If a regular expression ends with a greedy match (e.g. '.*')
  490.         or if more than one expression can match the same input, the
  491.         results are undeterministic, and may depend on the I/O timing.
  492.  
  493.         """
  494.         re = None
  495.         list = list[:]
  496.         indices = range(len(list))
  497.         for i in indices:
  498.             if not hasattr(list[i], 'search'):
  499.                 list[i] = re.compile(list[i])
  500.             
  501.         
  502.         while 1:
  503.             self.process_rawq()
  504.             for i in indices:
  505.                 m = list[i].search(self.cookedq)
  506.             
  507.             if self.eof:
  508.                 break
  509.             
  510.             if timeout is not None:
  511.                 (r, w, x) = select.select([
  512.                     self.fileno()], [], [], timeout)
  513.                 if not r:
  514.                     break
  515.                 
  516.             
  517.             self.fill_rawq()
  518.         text = self.read_very_lazy()
  519.         if not text and self.eof:
  520.             raise EOFError
  521.         
  522.         return (-1, None, text)
  523.  
  524.  
  525.  
  526. def test():
  527.     '''Test program for telnetlib.
  528.  
  529.     Usage: python telnetlib.py [-d] ... [host [port]]
  530.  
  531.     Default host is localhost; default port is 23.
  532.  
  533.     '''
  534.     debuglevel = 0
  535.     while sys.argv[1:] and sys.argv[1] == '-d':
  536.         debuglevel = debuglevel + 1
  537.         del sys.argv[1]
  538.     host = 'localhost'
  539.     if sys.argv[1:]:
  540.         host = sys.argv[1]
  541.     
  542.     port = 0
  543.     if sys.argv[2:]:
  544.         portstr = sys.argv[2]
  545.         
  546.         try:
  547.             port = int(portstr)
  548.         except ValueError:
  549.             port = socket.getservbyname(portstr, 'tcp')
  550.  
  551.     
  552.     tn = Telnet()
  553.     tn.set_debuglevel(debuglevel)
  554.     tn.open(host, port)
  555.     tn.interact()
  556.     tn.close()
  557.  
  558. if __name__ == '__main__':
  559.     test()
  560.  
  561.